import json
import time
from .getPublicData import *


def getBaseData():
    cars = getAllCars()
    # 车辆总数量
    sumCar = len(cars)
    # 销售最多的汽车
    highVolume = cars[0].saleVolume
    # 车型最多品牌
    topCar = cars[0].carName
    # 销量最多车型
    carModel = {}
    maxModel = 0
    mostModel = ''
    for car in cars:
        # 如果字典里面没有值 就要返回-1 有就执行else语句 同时给它+1
        if carModel.get(car.carModel,-1) == -1:
            carModel[str(car.carModel)] = 1
        else:
            carModel[str(car.carModel)] += 1
    carModel = sorted(carModel.items(), key=lambda x: x[1], reverse=True)
    # 赋值
    mostModel = carModel[0][0]
    # print(carModel)
    # print(carModel[0][0])
    # 品牌
    carBrand = {}
    maxBrand = 0
    mostBrand = ''
    for car in cars:
        if carBrand.get(car.brand, -1) == -1:
            carBrand[str(car.brand)] = 1
        else:
            carBrand[str(car.brand)] += 1
    # 使用循环的方式读取里面的k v
    for k, v in carBrand.items():
        if v > maxBrand:
            maxBrand = v
            mostBrand = k
    # print(maxBrand)
    # print(mostBrand)
    # 车辆平均价格
    carPrices = {}
    averagePrice = 0
    sumPrice = 0
    for car in cars:
        x = json.loads(car.price)[0]+ json.loads(car.price)[1]
        sumPrice += x
    averagePrice = sumPrice/(sumCar*2) # 平均价格=车辆总价格/车量总销量*2
    averagePrice = round(averagePrice,2) # 保留两位小数
    # print(averagePrice)
    return sumCar, highVolume, topCar, mostModel, mostBrand, averagePrice


def getRowData():
    cars = list(getAllCars())
    # 品牌的排行
    carBrands= {}
    for car in cars:
        if carBrands.get(car.brand,-1) == -1:
            carBrands[str(car.brand)] = 1
        else:
            carBrands[str(car.brand)] += 1
    brandList = [(value,key) for key,value in carBrands.items()]
    # 只需要20个
    brandList = sorted(brandList,reverse=True)[:20]
    # 转文字在前数字 在后
    sortDict = {car[1]: car[0] for car in brandList}
    lastSortList = []
    for k, v in sortDict.items():
        lastSortList.append({
            'name': k,
            'value': v
        })
    return lastSortList


# 能源占比 （油车 和 电车）
def getTypeRate():
    cars = list(getAllCars())
    carTypes={}
    for car in cars:
        if carTypes.get(car.energyType,-1) == -1:
            carTypes[str(car.energyType)]=1
        else:
            carTypes[str(car.energyType)] += 1

    print(carTypes)
    # 计算 油车
    oilRate = round(carTypes['汽油']/222 * 100,2)
    # 纯电车
    tramRate = round(carTypes['纯电动']/222 * 100,2)
    # 其他类型
    otherRate = round((222-carTypes['汽油']-carTypes['纯电动'])/222 * 100,2)
    return oilRate, tramRate, otherRate
